<template>
	<view class="main">
		<image :src="`${baseStaticFileUrl}/image/bindPhone/phoneImg.svg`" class="img"></image>
		<template v-if="type == 'wx'">
			<view class="tips">
				<u--text :text="bindWx?'已绑定微信':'未绑定微信'" :type="bindWx?'info':'error'"></u--text>
			</view>
			<view class="u-m-t-93">
				<u-button v-if="!bindWx" type="primary" text="绑定微信" :customStyle="wxBindBtnStyle"
					@click="bindWeiXinBtn()" />
				<view v-else>
					<u-modal :show="wxShow" content="确定要解除该微信号的绑定吗?" @confirm="relieveWxBtn" @cancel="wxShow=false"
						:showCancelButton="true"></u-modal>
					<!-- 					<u-input v-model="operatePassword" placeholder="请输入操作密码" border="bottom" 
						maxlength="11" disabledColor="none" />
					<view class="operate"></view> -->
					<u-button class="relieve" type="error" text="解绑" :customStyle="nextStepBtnCustomStyle"
						@click="wxShow=true">
					</u-button>
				</view>
			</view>
		</template>

		<template v-else>
			<view class="tips">
				<u--text :text="bindMobile?'已绑定手机号码':'未绑定手机号码'" :type="bindMobile?'info':'error'"></u--text>
			</view>
			<view class="input-info-phone" v-if="bindMobile">
				{{bindMobile}}
			</view>
			<view class="input-info" v-else>
				<u-input class="un" type="number" v-model="mobile" placeholder="请输入或获取手机号" border="bottom"
					maxlength="11" disabledColor="none">
					<template slot="suffix">
						<u-button :text="$u.test.isEmpty(mobile)?'获取手机号':'重新获取'" type="success" size="small"
							open-type="getPhoneNumber" @getphonenumber="getPhoneNumber" :customStyle="getCodeBtnStyle">
						</u-button>
					</template>
				</u-input>
				<u-input class="un" v-model="code" placeholder="请输入验证码" border="bottom" maxlength="6" type="number">
					<template slot="suffix">
						<u-code ref="uCode" @change="codeChange" seconds="60" changeText="X秒重新发送">
						</u-code>
						<u-button @tap="getCode" :text="tips" type="success" size="small"
							:customStyle="getCodeBtnStyle">
						</u-button>
					</template>
				</u-input>
			</view>
			<view class="u-m-t-93">
				<u-button v-if="!bindMobile" type="primary" text="确定" :customStyle="nextStepBtnCustomStyle"
					@click="bindMobileBtn"></u-button>
				<view v-else>
					<u-modal :show="show" content="确定要解除该手机号的绑定吗?" @confirm="relieveMobileBtn" @cancel="show=false"
						:showCancelButton="true"></u-modal>
					<u-input type="password" v-model="operatePassword" placeholder="请输入操作密码" border="bottom"
						maxlength="11" disabledColor="none" :clearable="true" />
					<view class="operate"></view>
					<u-button type="error" text="解绑" :customStyle="nextStepBtnCustomStyle" @click="show=true">
					</u-button>
				</view>

			</view>
		</template>

	</view>
</template>

<script>
	export default {
		data() {
			return {
				baseStaticFileUrl: this.$configPath.staticFileUrl,
				// 当前登录用户信息
				userInfo: {},
				show: false,
				wxShow: false,
				nextStepBtnCustomStyle: {
					width: '600rpx',
					height: '88rpx',
					borderRadius: '120px',
					color: '#fff',
				},
				wxBindBtnStyle: {
					width: '600rpx',
					height: '88rpx',
					borderRadius: '120rpx',
					background: '#6072FF',
					color: '#fff',
				},
				getCodeBtnStyle: {
					color: '#6072FF',
					background: 'none',
					border: 'none',
				},
				operate: {
					marginBottom: '40rpx',
				},

				// 注册类型：0没选，1微信手机号注册，2自定义手机号注册
				registerType: 0,
				mobile: '',
				bindMobile: '',
				bindWx: false,
				code: '',
				tips: '',
				verifyType: 1,

				type: '',
				operatePassword: '',
			}
		},
		onReady() {
			let title;
			if (this.type == 'wx') {
				title = "绑定微信"
			} else {
				title = "绑定手机号"
			}
			uni.setNavigationBarTitle({
				title: title
			})
		},
		onLoad(options) {
			this.type = options.options;
			this.getUserInfo();
		},
		methods: {

			getPhoneNumber(e) {
				try {
					// console.info(e);
					if (e.detail.errMsg == "getPhoneNumber:fail:user deny" || e.detail.errMsg ==
						"getPhoneNumber:fail user deny") {
						// 拒绝授权
						return;
					} else if (e.detail.errMsg != 'getPhoneNumber:ok') {
						getApp().err('获取手机号不成功：' + e.detail.errMsg);
						return;
					}

					uni.showLoading({
						title: '获取中...',
						mask: true
					});

					let params = {
						iv: e.detail.iv,
						encryptedData: e.detail.encryptedData
					};
					this.$api('applet.getPhoneNumberv2', params).then(res => {
						uni.hideLoading();
						if (res.status == 0) {
							this.mobile = res.data.mobile;
						} else {
							getApp().err('请求不成功:' + res.msg);
						}
					}).catch(err => {
						uni.hideLoading();
					})
				} catch (err) {
					uni.hideLoading();
					console.error('getPhoneNumber捕抓到异常' + err.message);
				}
			},
			codeChange(text) {
				this.tips = text;
			},
			// 获取验证码
			getCode() {
				if (!this.$refs.uCode.canGetCode) {
					return;
				}

				if (this.$u.test.isEmpty(this.mobile)) {
					this.$helpers.toast('手机不能为空');
					return;
				}

				uni.showLoading({
					title: '发送中',
					mask: true,
				})

				let params = {
					mobile: this.mobile,
					verifyType: this.verifyType
				}
				this.$api('user.smsCode', params).then(res => {
					if (res.status == 0) {
						uni.hideLoading();
						this.$refs.uCode.start();
						this.$helpers.toast('验证码已发送');
					} else {
						uni.hideLoading();
						this.$helpers.toast('短信发送失败：' + res.msg);
					}
				})

			},
			//绑定手机号
			bindMobileBtn() {
				if (this.$u.test.isEmpty(this.mobile)) {
					this.$helpers.toast('请输入手机号');
					return
				}
				if (!/^1[3456789]\d{9}$/.test(this.mobile)) {
					this.$helpers.toast('请输入正确的手机号');
					return
				}
				if (!this.$u.test.mobile(this.mobile)) {
					this.$helpers.toast('手机号格式有误');
					return
				}

				if (this.$u.test.isEmpty(this.code)) {
					this.$helpers.toast('请输入验证码');
					return
				}
				let params = {
					smsCode: this.code,
					mobile: this.mobile,
				}
				uni.showLoading({
					title: '绑定中',
					mask: true,
				})
				this.$api("user.updateMobile", params).then(res => {
					console.log(res)
					uni.hideLoading();
					if (res.status == 0) {
						this.$helpers.toast("绑定成功")
						this.getUserInfo();
					} else {
						getApp().err('绑定失败：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			//解除手机号绑定
			relieveMobileBtn() {
				let reg = /^\S+$/
				if (!reg.test(this.operatePassword)) {
					this.show = false
					getApp().err('操作密码不能为空，且不能为空格');
					return
				}
				let params = {
					operatePassword: this.operatePassword,
					mobile: "",
					unbindType: "mobile",
				}
				uni.showLoading({
					title: '解绑中',
					mask: true,
				})
				this.$api("user.unbindMobileOrWeChat", params).then(res => {
					uni.hideLoading();
					if (res.status == 0) {
						this.show = false
						this.mobile = ''
						this.code = ''
						this.bindMobile = '';
						this.operatePassword = ''
						this.$helpers.toast("解绑成功")
						this.getUserInfo();
					} else {
						this.show = false
						getApp().err('解绑不成功：' + res.msg);
					}
				}).catch(err => {
					uni.hideLoading();
				})
			},
			// 绑定微信 
			bindWeiXinBtn() {
				var that = this;
				uni.login({
					provider: 'weixin',
					success: function(loginRes) {
						uni.showLoading({
							title: '授权中...',
							mask: true
						});

						let params = {
							code: loginRes.code,
							appId: uni.getAccountInfoSync().miniProgram.appId
						};

						that.$api('applet.bindWeXin', params).then(res => {
							uni.hideLoading();
							if (res.status == 0) {
								if (res.data) {
									that.getUserInfo();
									that.$helpers.toast("绑定成功")
								} else {
									getApp().err(
										'该微信号已经绑定过其他账号，无法绑定当前帐号'
									);
								}
							}
						}).catch(err => {
							uni.hideLoading();
						})
					},
				})
			},
			//移除微信绑定
			relieveWxBtn() {
				var that = this;
				uni.login({
					provider: 'weixin',
					success: function(res) {
						console.log("我要开始解绑了", res)
						let params = {
							code: res.code,
							unbindType: "wx",
						}
						uni.showLoading({
							title: '解绑中',
							mask: true,
						})
						that.$api("user.unbindMobileOrWeChat", params).then(res => {
							uni.hideLoading();
							if (res.status == 0) {
								that.wxShow = false
								that.bindWx = '';
								that.$helpers.toast("解绑成功")
								that.getUserInfo();
							} else {
								that.wxShow = false
								getApp().err('解绑不成功：' + res.msg);
							}
						}).catch(err => {
							uni.hideLoading();
						})
					},
					fail: function(res) {
						console.log(res);
					},
				})
			},

			getUserInfo() {
				this.$api('user.getMobileAndUnionId').then(res => {
					if (res.status == 0) {
						this.userInfo = res.data;
						if (this.userInfo.mobile) {
							this.bindMobile = this.userInfo.mobile
						}
						if (this.userInfo.unionId) {
							this.bindWx = this.userInfo.unionId
						}
						this.$store.commit("SET_USER_INFO", this.userInfo);
					}
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	.main {

		color: rgba(0, 0, 0, 0.8);
		display: flex;
		align-items: center;
		flex-direction: column;

		.img {
			width: 290rpx;
			height: 290rpx;
			margin-top: 130rpx;
		}

		.tips {
			margin-top: 60rpx;
			font-size: $f-sm;
		}

		.input-info {
			margin-top: 100rpx;

			.un-input {
				margin: 10rpx 0;
			}

			.get-mobile-btn {
				color: #6072FF;
				background: none;
				// padding: 0;
			}
		}

		.input-info-phone {
			margin-top: 10rpx;
			font-size: 20px;
		}

		.btnBinding {
			margin-top: 60rpx;

		}

		.operate {
			margin-bottom: 36rpx;
		}
	}
</style>